package com.cloudm.technician.extensions

import android.app.Activity
import android.content.Intent
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.cloudm.technician.R

/**
 * 作者: wesley
 * 时间: 2017/11/20
 * 描述: activity的扩展函数
 */

/**
 * 隐藏软键盘
 */
fun AppCompatActivity.hideSoftKeyboard() {
    var view: View? = this.currentFocus
    if (view == null) {
        view = View(this)
    }
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE)
    imm as? InputMethodManager ?: return
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}


/**
 * 界面跳转
 */
fun AppCompatActivity.openActivityForResult(intent: Intent, requestCode: Int) {
    startActivityForResult(intent, requestCode)
}


/*
 * 界面跳转
 */
fun <T> AppCompatActivity.openActivityForResult(target: Class<T>, requestCode: Int) {
    val intent = Intent(this, target)
    openActivityForResult(intent, requestCode)
}


/**
 * fragment添加到activity中
 */
fun AppCompatActivity.addFragmentToActivity(manager: FragmentManager, fragment: Fragment?,
                                            tag: String? = null,
                                            containerViewId: Int = R.id.common_content) {

    fragment?.let {
        when (it.isAdded) {
            false -> {
                manager.beginTransaction().apply {
                    add(containerViewId, fragment, tag)
                }.commit()
            }

            else -> {
                logger_e(" fragment is added! $it")
            }
        }
    }
}

